<template>
  <div class="page-container">
    <!-- 语言选择 -->
    <!-- <li style="display: flex; justify-content: flex-end; padding-top: 32px">
      <el-select v-model="currentLan" @change="selectLanguage" placeholder="请选择" size="mini" class="inputStyle">
        <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value"></el-option>
      </el-select>
    </li>-->
    <!-- 选择账套 账套列表存在且不为空 -->
    <div v-if="accountList && accountList.length > 0" class="select-account-view">
      <div class="select-title">请选择您要使用的账套</div>
      <div style="width: 100%; display: flex; justify-content: center">
        <div class="account-list">
          <div class="account-item" :class="item.used ? 'select-account-item' : ''" v-for="(item, index) in accountList"
            :key="index" @click="editAccountInfo(item)">
            <div class="com-name">{{ item.companyName }}</div>
            <div style="margin-top: 0.675042rem">
              <div class="product-info">产品类型：{{  item.version || '标准财务版' }}</div>
              <!-- <div class="product-info">启用时间：{{ item.enableDate }}</div> -->
            </div>
            <img v-if="item.used" class="img-used" :src="require('../../assets/login/icon_used.png')" alt />
          </div>
        </div>
      </div>
      <div
        style="width: 100%; display: flex; justify-content: center; margin-top: 1.687605rem; margin-bottom: 2.343896rem">
        <img class="logo" :src="require('../../assets/login/logo_trans.png')" alt />
      </div>
    </div>
    <!-- 创建账套 账套列表不存在或为空 -->
    <div v-else class="create-account-view">
      <!-- 版本选择界面 -->
      <div v-if="showVersionSelect" class="version-select-view">
        <div class="select-title">请选择您要使用的版本</div>
        <div class="version-list">
          <div v-for="(version, index) in versionList" :key="index" class="version-card">
            <div class="version-name">{{version.name}} <div class="version-user-limit" v-if="version.name === '必用版'">不限用户</div></div>
            <div class="version-desc">{{version.description}}</div>
            <el-button class="free-trial-btn" type="primary" @click="selectVersion(version)">免费试用</el-button>
            <div class="version-date">免费试用期限为7天</div>
          </div>
        </div>
        <div style="width: 100%; display: flex; justify-content: center; margin-top: .875rem;">
          <img class="logo" :src="require('../../assets/login/logo_trans.png')" alt />
        </div>
      </div>
      <!-- 创建账套表单 -->
      <div v-else>
        <div style="width: 100%; display: flex; justify-content: center">
          <img class="logo" :src="require('../../assets/login/logo_trans.png')" alt />
        </div>
        <div class="create-card">
          <div>
            <div class="create-title">创建账套</div>
            <el-form ref="form" :model="form" :rules="rules" label-width="80px" class="form-view">
              <el-form-item label="公司名称" prop="companyName">
                <el-input v-model="form.companyName"></el-input>
              </el-form-item>
              <!-- <el-form-item label="启用时间" prop="enableDate">
                <el-date-picker type="date" placeholder="启用时间" v-model="form.enableDate"
                  style="width: 100%" :picker-options="pickerOptions" value-format="yyyy-MM-dd"></el-date-picker>
              </el-form-item>-->
              <el-form-item label="币种符号" prop="currencyType">
                <j-dict-select-tag type="select" dictCode="currency_type" style="width:100%;" v-model="form.currencyType"
                  placeholder="请选择币种符号"></j-dict-select-tag>
              </el-form-item>
              <el-button class="btn" type="primary" @click="nextStep">下一步</el-button>
            </el-form>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { getAction, postAction } from '../../api/manage'
import Vue from 'vue'
import {
  ACCESS_TOKEN,
  USER_NAME,
  USER_INFO,
  USER_AUTH,
  SYS_BUTTON_AUTH,
  UI_CACHE_DB_DICT_DATA,
  TENANT_ID,
  CACHE_INCLUDED_ROUTES,
  ACCOUNT_BOOK,
} from '@/store/mutation-types'
//这里可以导入其它文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
//例如：import 《组件名称》from ‘《组件路径》';

export default {
  //import引入的组件需要注入到对象中才能使用
  name: 'CreateAccount',
  components: {},
  props: {
    state: {
      type: String,
      default: ''
    }
  },
  data() {
    //这里存放数据
    return {
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 24 * 60 * 60 * 1000;
        },
      },
      // 语言选择
      options: [
        {
          value: '1',
          label: '中文',
        },
        {
          value: '3',
          label: '繁体',
        },
        {
          value: '2',
          label: 'EN',
        },
      ],
      currentLan: '1',
      langcn: 'cn',
      langen: 'en',
      langtw: 'tw',
      form: {
        companyName: '',
        // enableDate: '',
        currencyType: '1',
      },
      // 账套列表
      accountList: [],
      userInfo: Vue.ls.get(USER_INFO),
      accountInfo: Vue.ls.get(ACCOUNT_BOOK) || {},
      rules: {
        companyName: [
          { required: true, message: '请输入公司名称', trigger: 'blur' },
        ],
        // enableDate: [
        //   { type: 'string', required: true, message: '请选择启用日期', trigger: 'change' }
        // ],
        currencyType: [
          { required: true, message: '请选择货币', trigger: 'change' }
        ]
      },
      timer: null,
      showVersionSelect: false,
      selectedVersion: null,
      versionList: [ // 版本列表
        {
          name: '必用版',
          description: '小微商家必备'
        },
        {
          name: '专业版',
          description: '全行业通用，功能强大'
        },
        {
          name: '高级版',
          description: '特色功能模块更智能'
        },
        {
          name: '标准财务版',
          description: '进销存财务一体化管理'
        }
      ],
    }
  },
  //计算属性 类似于data概念
  computed: {},
  //监控data中数据变化
  watch: {},
  //生命周期 - 创建完成（可以访问当前this实例）
  created() {
    console.log(this.$i18n.locale)
    switch (this.$i18n.locale) {
      case 'cn':
        this.currentLan = '1'
        break
      case 'en':
        this.currentLan = '2'
        break
      case 'tw':
        this.currentLan = '3'
        break

      default:
        break
    }
  },
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {
    if (!this.state) {
      this.getAccountList()
    }
  },
  //生命周期-创建之前
  beforeCreated() { },
  //生命周期-挂载之前
  beforeMount() { },
  //生命周期-更新之前
  beforUpdate() { },
  //生命周期-更新之后
  updated() { },
  //生命周期-销毁之前
  beforeDestory() { },
  //生命周期-销毁完成
  destoryed() { },
  //如果页面有keep-alive缓存功能，这个函数会触发
  activated() { },
  //方法集合
  methods: {
    // 获取账套列表
    getAccountList() {
      const that = this
      getAction(`accountbookinfo/xghAccountBook/getAccountBookByUserId/${this.userInfo.id}`).then((res) => {
        if (res.code == 200) {
          that.accountList = res.result || []
          // that.accountList.forEach((item) => {
          //   if (that.accountInfo.id && item.id == that.accountInfo.id) {
          //     that.$set(item, 'used', true)
          //   } else {
          //     that.$set(item, 'used', false)
          //   }
          // })
        } else {
          this.$elMessage.error(res.message)
        }
      })
    },
    // 切换语言
    selectLanguage() {
      switch (this.currentLan) {
        case '1':
          this.$i18n.locale = this.langcn
          localStorage.lang = this.langcn
          break
        case '2':
          this.$i18n.locale = this.langen
          localStorage.lang = this.langen
          break
        case '3':
          this.$i18n.locale = this.langtw
          localStorage.lang = this.langtw
          break

        default:
          break
      }
      console.log(this.$i18n.messages.en.message.hello)
    },
    nextStep() {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          // 判断公司名称是否存在
          let result = await postAction('/accountbookinfo/xghAccountBook/companyNameExists', {
            companyName: this.form.companyName
          })
          if (result.success) {
            if(result.result) {
              this.showVersionSelect = true;
            } else {
              this.$elMessage.error('公司名称已存在')
            }
          } else {
            this.$elMessage.error(result.message)
          }
        }
      })
    },
    selectVersion(version) {
      this.selectedVersion = version;
      this.form.version = version.name;
      this.onSubmit();
    },
    onSubmit () {
      const that = this
      let number = 20
      const loading = that.$loading({
        lock: true,
        text: '账套新增中，请耐心等待，预计剩余20s...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.8)',
      });
      if (that.timer) {
        clearInterval(that.timer)
      }
      that.timer = setInterval(() => {
        setTimeout(() => {
          if (number > 0) {
            number--
            loading.setText(`账套新增中，请耐心等待，预计剩余${number}s...`)
          } else {
            clearInterval(that.timer)
            loading.close()
          }
        }, 0);
      }, 1000)
      postAction('/accountbookinfo/xghAccountBook/add', this.form).then(res => {
        clearInterval(that.timer)
        loading.close()
        if (res.success) {
          this.$elMessage.success(res.message)
          // this.$refs.form.resetFields();
          // setTimeout(() => {
          this.getAccountList()
          // }, 1000);
        } else {
          this.$elMessage.error(res.message)
        }
      })
    },
    switchAccount(item) {
      this.accountList.forEach((element) => {
        if (element.id == item.id) {
          if (this.accountInfo.id) {
            this.editAccountInfo(element)
          } else {
            this.addAccountInfo(element)
          }
        } else {
          element.used = false
        }
      })
      setTimeout(() => {
        this.$router.push({ path: '/dashboard/analysis' })
      }, 1000)
    },
    // 添加账套
    addAccountInfo(item) {
      postAction('/accountbookinfo/xghAccountBook/add', {
        accountBookId: item.id,
        userId: this.userInfo.id,
      }).then(res => {
        if (res.code == 200) {
          Vue.ls.set(ACCOUNT_BOOK, item)
          item.used = true
        } else {
          this.$elMessage.error(res.message)
        }
      })
    },
    // 更新账套
    editAccountInfo(item) {
      const that = this
      let number = 20
      const loading = that.$loading({
        lock: true,
        text: '账套选择中，请耐心等待，预计剩余20s...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.8)',
      });
      if (that.timer) {
        clearInterval(that.timer)
      }
      that.timer = setInterval(() => {
        setTimeout(() => {
          if (number > 0) {
            number--
            loading.setText(`账套选择中，请耐心等待，预计剩余${number}s...`)
          } else {
            clearInterval(that.timer)
            loading.close()
          }
        }, 0);
      }, 1000)
      postAction('accountbookusing/xghAccountBookUserUsing/updateByUserId', {
        accountBookId: item.id,
        userId: this.userInfo.id,
      }).then(res => {
        clearInterval(that.timer)
        loading.close()
        if (res.code == 200) {
          Vue.ls.set(ACCOUNT_BOOK, { id: item.id })
          let userPerms = res.result || {}
          this.$lcStorage.set('userPermissions', userPerms)
          item.used = true
          this.$router.push({ path: '/dashboard/analysis' })
        } else {
          this.$elMessage.error(res.message)
        }
      })
    },
  },
}
</script>
<style lang='scss' scoped>
/* @import url(); 引入css类 */
.page-container {
  margin: 0;
  padding: 0;
  width: 100%;
  height: 100%;
  background: #e3f6ff;
  opacity: 1;
  overflow-y: scroll;
}

// .inputStyle {
//     position:absolute;
//     // clip:rect(2px 90px 30px 2px);
//     width:90px;
//     height:28px;
//     line-height:28px;
//     font-size:15px;
//     font-weight:bold;

//   }
.inputStyle {
  width: 1.500094rem;
  // 未选中任何选项的时候 placeholder的样式 需要先选中父元素 增加权重
  //   /deep/ input::-webkit-input-placeholder {
  //     color: #fff;
  //   }
  //   /deep/  input::-moz-input-placeholder {
  //     color: #fff;
  //   }
  //   /deep/  input::-ms-input-placeholder {
  //     color: #fff;
  //   }

  //   //修改的是el-input的样式
  //   //一种方法是设置最里层el-input__inner的背景色 外层的两级父元素设置为透明色
  //   //另一种方法是从el-select到el-input__inenr的背景色都设置为需要的颜色
  //   /deep/ .el-select,
  //   /deep/ .el-input,
  ::v-deep .el-input__inner {
    background-color: #e3f6ff;
    color: #666666;
    border: 0px;
    border-radius: 0px;
    text-align: center;
  }

  //el-input聚焦的时候 外层的border会有一个样式
  ::v-deep .el-select .el-input.is-focus .el-input__inner {
    border: 0px;
  }

  //修改的是el-input上下的小图标的颜色
  ::v-deep .el-select .el-input .el-select__caret {
    color: #fff;
  }

  //修改总体选项的样式 最外层
  ::v-deep .el-select-dropdown {
    background-color: #e3f6ff;
    margin: 0px;
    border: 0px;
    border-radius: 0px;
  }

  //修改单个的选项的样式
  ::v-deep .el-select-dropdown__item {
    background-color: transparent;
    color: #fff;
  }

  //item选项的hover样式
  ::v-deep .el-select-dropdown__item.hover,
  ::v-deep .el-select-dropdown__item:hover {
    color: #e3f6ff;
  }

  //修改的是下拉框选项内容上方的尖角
  ::v-deep .el-popper .popper__arrow,
  .el-popper .popper__arrow::after {
    display: none;
  }
}

.create-account-view {
  display: flex;
  justify-content: center;
  position: relative;
  margin-top: 1.368836rem;

  .create-card {
    position: relative;
    margin-top: -0.225014rem;
    width: 10.313145rem;
    // height: 7.294206rem;
    background: #ffffff;
    opacity: 1;
    border-radius: 0.375023rem;
    display: flex;
    justify-content: center;
    padding-bottom: 30px;

    .create-title {
      font-size: 0.56rem;
      font-family: PingFang SC;
      font-weight: 500;
      line-height: 0.787549rem;
      color: #666666;
      opacity: 1;
      margin-top: 0.56rem;
      display: flex;
      justify-content: center;
    }

    .form-view {
      margin-top: 0.375023rem;
      margin-left: 1.743859rem;
      margin-right: 1.91262rem;
    }

    .btn {
      width: 7.031689rem;
      margin-top: 0.7rem;
      height: 0.937559rem;
      display: inline-block;
    }
  }
}

.select-account-view {
  .select-title {
    font-size: 0.56rem;
    font-family: PingFang SC;
    font-weight: 500;
    line-height: 0.787549rem;
    color: #666666;
    opacity: 1;
    margin-top: 1.218826rem;
    width: 100%;
    display: flex;
    justify-content: center;
  }

  .account-list {
    margin-top: 1rem;
    // width: 100%;
    display: flex;
    flex-wrap: wrap;
    // justify-content: space-between;
    padding-left: 2rem;
    padding-right: 2rem;

    .account-item {
      width: 6.3rem;
      height: 3.75rem;
      background: #ffffff;
      border: 1px solid #77c1ff;
      opacity: 1;
      border-radius: 0.187512rem;
      margin: 0.56rem 0.16rem 0;
      color: #666666;
      padding-left: 0.543784rem;
      padding-top: 0.768798rem;
    }

    .select-account-item {
      width: 6.3rem;
      height: 3.75rem;
      background: #1993fb;
      opacity: 1;
      border-radius: 0.187512rem;
      margin: 0.56rem 0.16rem 0;
      color: #ffffff;
      padding-left: 0.543784rem;
      padding-top: 0.768798rem;
      position: relative;
    }

    .com-name {
      font-size: 0.3rem;
      font-family: PingFang SC;
      font-weight: 600;
      line-height: 0.412526rem;
      opacity: 1;
    }

    .product-info {
      font-size: 0.225014rem;
      font-family: PingFang SC;
      font-weight: 400;
      line-height: 0.356272rem;
      opacity: 1;
    }

    .img-used {
      position: absolute;
      top: -1px;
      right: -1px;
      width: 1.181324rem;
      height: 1.181324rem;
    }
  }
}

.logo {
  width: 7.087943rem;
  height: 1.27508rem;
  opacity: 1;
}

.version-select-view {
  position: relative;
  margin-top: -0.225014rem;
  width: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;

  .select-title {
    font-size: 0.56rem;
    font-family: PingFang SC;
    font-weight: 500;
    line-height: 0.787549rem;
    color: #666666;
    opacity: 1;
    margin-bottom: 1rem;
  }

  .version-list {
    display: flex;
    flex-wrap: wrap;
    justify-content: center;
    gap: 0.3rem;
    // max-width: 1200px;
    padding: 0 1rem;
  }

  .version-card {
    padding: .475rem .4125rem;
    transition: all 0.3s;
    width: 4.275rem;
    height: 3.6rem;
    background: #ffffff;
    border: 1.5px solid #77c1ff;
    opacity: 1;
    border-radius: 0.187512rem;
    margin: 0.56rem 0.16rem 0;
    color: #666666;

    &:hover {
      transform: translateY(-5px);
      box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
    }

    .version-name {
      font-size: .4rem;
      font-weight: 600;
      color: #0082F1;
      margin-bottom: .125rem;
      display: flex;
      align-items: center;
    }

    .version-user-limit{
      padding: .07rem .1rem;
      background: #F1F1F1;
      color: #999999;
      font-size: .25rem;
      border-radius: .05rem;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-left: .2rem;
      font-weight: normal;
      letter-spacing: .04rem;
    }

    .version-desc {
      font-size: .24rem;
      color: #666;
      margin-bottom: .3125rem;
    }

    .free-trial-btn {
      font-size: .2rem;
      width: 1.875rem;
      margin-bottom: .25rem;
      // height: .375rem;
      // display: inline-block;
    }

    .version-date {
      font-size: .24rem;
      color: #999999;
    }
  }
}
</style>